<template>
	<main class="app-login">
		<el-card class="app-login-card" :body-style="bodyStyle">
			<template #header>
				<header>系统登录</header>
			</template>
			<el-form ref="formRef" :model="form" :rules="rules" size="medium">
				<el-form-item prop="username">
					<el-input
						v-model.trim="form.username"
						placeholder="账号"
						prefix-icon="el-icon-user"
						maxlength="18"
						clearable
					/>
				</el-form-item>
				<el-form-item prop="password">
					<el-input
						v-model.trim="form.password"
						placeholder="密码"
						prefix-icon="el-icon-lock"
						type="password"
						maxlength="18"
						show-password
						clearable
					/>
				</el-form-item>
				<el-form-item>
					<el-button class="w-full" type="primary" :loading="loading" @click="submitForm('formRef')">登录</el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<footer>
			<el-link class="footer-text" :underline="false" href="https://zxkv.github.io" target="_blank">
				© {{ fullYear }} 🍀 下落香樟树
			</el-link>
		</footer>
	</main>
</template>

<script>
import { mapActions } from "vuex";

import { validateForm } from "@/tools";
import { createToken, setToken } from "@/tools/auth";

export default {
	name: "Login",
	data() {
		return {
			loading: false,
			bodyStyle: {
				paddingTop: "22px"
			},
			fullYear: new Date().getFullYear(),
			form: {
				username: "",
				password: ""
			},
			rules: {
				username: [{ required: true, message: "请输入账号", trigger: "blur" }],
				password: [{ required: true, message: "请输入密码", trigger: "blur" }]
			}
		};
	},
	methods: {
		...mapActions("user", ["setUser", "setUserToken"]),
		async submitForm(formRef) {
			const isPass = await validateForm(this.$refs[formRef]);
			if (isPass) {
				this.loading = true;
				const token = createToken(this.form);
				this.setUser(this.form);
				setToken(token);
				this.setUserToken(token);
				this.$router.push({ path: "/", replace: true });
				this.loading = false;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.app-login {
	box-sizing: border-box;
	width: 100dvw;
	height: 100dvh;
	overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
	user-select: none;
	transition: 0.6s;
	background-size: 200% auto;
	background-image: linear-gradient(to right, #165dff 0%, #021b79 51%, #165dff 100%);
	&:hover {
		background-position: right center;
	}

	.app-login-card {
		width: 360px;
		min-height: 248px;
		height: auto;

		header {
			width: 100%;
			font-size: 20px;
			text-align: center;
			font-weight: 500;
		}
	}

	footer {
		width: 100%;
		height: 32px;
		line-height: 32px;
		font-size: 14px;
		text-align: center;
		position: fixed;
		bottom: 0;
		left: 0;
		.footer-text {
			color: #fafafa;
			&:hover {
				opacity: 0.6;
			}
		}
	}
}
</style>
